package com.filldream.fastboot.common.okutil;

import cn.hutool.core.date.DateUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.filldream.fastboot.common.constant.FinalStr;
import com.filldream.fastboot.common.entity.SendDdRobotSTO;
import com.filldream.fastboot.common.okutil.cls.dto.ClsNewsSimpleItem;
import com.filldream.fastboot.common.util.DDErrorUtil;
import com.filldream.fastboot.common.util.HttpUtil;
import com.filldream.fastboot.common.util.JsonUtil;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * 财经机器人工具类
 */
@Slf4j
public class RobotUtil {

    /**
     * 周老板飞书消息
     * @param addList
     */
    public static void autoFs(List<ClsNewsSimpleItem> addList){
        if( ObjectUtils.isEmpty(addList) ){
            return;
        }
        List<List<Map<String,Object>>> fsNews = new ArrayList<>();
        for (int i = 0; i < addList.size(); i++) {
            ClsNewsSimpleItem item = addList.get(i);
            fsNews.add(item.initFeiShu(i+1));
        }
        String temp = "{\"msg_type\":\"post\",\"content\":{\"post\":{\"zh_cn\":{\"title\":\"财联社消息\",\"content\":news}}}}";
        temp = temp.replace("news", JsonUtil.toJson(fsNews));
        //发送飞书消息
        try {
            HttpUtil.doPost(FinalStr.getFsUrl(), temp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送财联社消息给钉钉
     * @param addList
     */
    public static void autoDD( List<ClsNewsSimpleItem> addList ) {
        if( ObjectUtils.isNotEmpty( addList) ){
            ClsNewsSimpleItem firstItem = addList.get(0);
            StringBuilder content = new StringBuilder();
            for (int i = 0; i < addList.size(); i++) {
                ClsNewsSimpleItem item = addList.get(i);
                if( item.getIsTop() ){
                    content.append("[**<font color=\"#ff0000\">"+ (i+1) +"、"+item.getTitle()+"</font>**]("+item.getLinkUrl()+")\n\n");

                }else{
                    content.append("["+ (i+1) +"、"+item.getTitle()+"]("+item.getLinkUrl()+")\n\n");
                }
            }

            SendDdRobotSTO.Markdown markdown = new SendDdRobotSTO.Markdown();
            markdown.setText(  content.toString() );
            markdown.setTitle( firstItem.getTitle() );
            SendDdRobotSTO sto = new SendDdRobotSTO();
            sto.setMsgtype("markdown");
            sto.setMarkdown( markdown );
            DDErrorUtil.sendDd(FinalStr.getDdUrl(),sto );
        }
    }

    /**
     * 是否夜间休息时间，夜间休息时间，不推送机器人
     * @return
     */
    public static Boolean isSleepTime(){
        Date currentTime = new Date();
        int hour = DateUtil.hour(currentTime, true);
        int minute = DateUtil.minute(currentTime);
        return ( hour >= 22 &&  minute >=0 )
                || (
                (hour < 7 && minute >= 0 )
                        || (hour == 7 && minute < 35)
        );
    }

    /**
     * 发送钉钉卡片消息
     * @param newsList     新闻列表
     * @param btnMap       按钮映射
     */
    public static void autoDD( List<ClsNewsSimpleItem> newsList,Map<String,String> btnMap ) {
        if( ObjectUtils.isNotEmpty( newsList) ){
            StringBuilder content = new StringBuilder();
            for (int i = 0; i < newsList.size(); i++) {
                ClsNewsSimpleItem item = newsList.get(i);
                if( item.getIsTop() ){
                    content.append("[**<font color=\"#ff0000\">"+ (i+1) +"、"+item.getTitle()+"</font>**]("+item.getLinkUrl()+")\n\n");
                }else{
                    content.append("["+ (i+1) +"、"+item.getTitle()+"]("+item.getLinkUrl()+")\n\n");
                }
            }

            DingTalkClient client = new DefaultDingTalkClient(FinalStr.getDdUrl());
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype("actionCard");

            OapiRobotSendRequest.Actioncard actioncard = new OapiRobotSendRequest.Actioncard();
            actioncard.setTitle(newsList.get(0).getTitle());
            actioncard.setText(content.toString());

            List<OapiRobotSendRequest.Btns> btnsList = new LinkedList<>();
            btnMap.forEach( (title,actionUrl) -> {
                OapiRobotSendRequest.Btns btns = new OapiRobotSendRequest.Btns();
                btns.setTitle(title);
                btns.setActionURL(actionUrl);
                btnsList.add(btns);
            });
            if(  ObjectUtils.isNotEmpty(btnsList) ){
                actioncard.setBtns( btnsList );
            }
            request.setActionCard(actioncard);
            try {
                client.execute(request);
            } catch (ApiException e) {
                log.error("钉钉机器人发送失败",e);
            }
        }
    }

    /**
     * 发送钉钉markdown-图片消息
     * @param title 标题
     * @param imgUrl    图片地址
     * @param otherText 其他markdown格式
     */
    public static void autoDD( String title,String imgUrl,String otherText ) {
        DingTalkClient client = new DefaultDingTalkClient(FinalStr.getDdUrl());
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("markdown");
        OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
        String text = "[!["+title+"]("+imgUrl+" \""+title+"\")]("+imgUrl +" \""+title+"\")";
        if(StringUtils.isNotBlank(otherText)){
            text = text + "\n\n" + otherText;
        }
        markdown.setText(text);
        markdown.setTitle(title);
        request.setMarkdown(markdown);
        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
        at.setIsAtAll(true);
        request.setAt( at );
        try {
            client.execute(request);
        } catch (ApiException e) {
            throw new RuntimeException(e);
        }
    }

}
